import asyncio
import logging
import json
import os


from ronglian_sms_sdk import SmsSDK
from django.conf import settings
from concurrent.futures import ThreadPoolExecutor

logger = logging.getLogger(__name__)

# 线程池用于异步执行同步代码
thread_pool = ThreadPoolExecutor(max_workers=10)


class RonglianSMSService:
    def __init__(self):
        # 从环境变量获取认证信息
        acc_id = os.getenv('ACC_ID')
        acc_token = os.getenv('ACC_TOKEN')
        app_id = os.getenv('APP_ID')

        # 检查必要的环境变量是否设置
        if not all([acc_id, acc_token, app_id]):
            raise ValueError("缺少必要的环境变量: ACC_ID, ACC_TOKEN, APP_ID")

        # 初始化SDK实例
        self.sdk = SmsSDK(acc_id, acc_token, app_id)

    def _send_sms_sync(self, phone, code):
        """
        同步发送短信（在线程池中执行）
        """
        try:
            tid = '1'
            mobile = phone  # 单个手机号
            datas = (code, '5')  # 验证码和有效期（分钟）

            # 调用荣联云SDK发送短信
            resp = self.sdk.sendMessage(tid, mobile, datas)

            # 解析响应
            response_data = self._parse_response(resp)
            logger.info(f"发送短信: {phone}, 响应: {response_data}")

            if response_data.get('statusCode') == '000000':
                logger.info(f"荣联云短信发送成功: {phone}, 消息ID: {response_data.get('smsMessageSid')}")
                return True, response_data
            else:
                logger.error(
                    f"荣联云短信发送失败: {phone}, 错误码: {response_data.get('statusCode')}, 错误信息: {response_data.get('statusMsg')}")
                return False, response_data

        except Exception as e:
            logger.error(f"荣联云短信发送异常: {phone}, 错误: {e}")
            return False, {'error': str(e)}

    def _parse_response(self, resp):
        """
        解析荣联云SDK响应
        """
        try:
            # 荣联云SDK返回的是字符串，需要解析
            import json
            return json.loads(resp)
        except json.JSONDecodeError:
            logger.error(f"响应解析失败: {resp}")
            return {'statusCode': '999999', 'statusMsg': '响应解析失败'}
        except Exception as e:
            logger.error(f"响应处理异常: {e}")
            return {'statusCode': '999999', 'statusMsg': str(e)}

    async def send_verification_code_async(self, phone, code):
        """
        异步发送验证码短信 - 使用荣联云官方SDK
        """
        try:
            # 在线程池中执行同步的SDK调用
            loop = asyncio.get_event_loop()
            success, response_data = await loop.run_in_executor(
                thread_pool,
                self._send_sms_sync,
                phone,
                code
            )

            return success

        except asyncio.TimeoutError:
            logger.error(f"荣联云短信发送超时: {phone}")
            return False
        except Exception as e:
            logger.error(f"荣联云短信发送异常: {phone}, 错误: {e}")
            return False

    async def send_verification_code_with_retry(self, phone, code, retry_times=3):
        """
        带重试机制的短信发送
        """
        for attempt in range(retry_times):
            try:
                success = await self.send_verification_code_async(phone, code)
                if success:
                    return True

                logger.warning(f"第{attempt + 1}次发送失败，准备重试...")
                await asyncio.sleep(1)  # 等待1秒后重试

            except Exception as e:
                logger.error(f"第{attempt + 1}次发送异常: {e}")
                await asyncio.sleep(1)

        logger.error(f"短信发送重试{retry_times}次均失败: {phone}")
        return False

    # async def send_batch_sms_async(self, phones, codes):
    #     """
    #     批量发送短信（使用官方SDK的批量接口）
    #     """
    #     try:
    #         if len(phones) != len(codes):
    #             raise ValueError("手机号和验证码数量不匹配")
    #
    #         # 批量发送（荣联云支持逗号分隔的手机号）
    #         tid = self.config['TEMPLATE_ID']
    #         mobile = ','.join(phones)
    #
    #         # 所有验证码使用相同的模板变量（如果需要不同的变量，需要特殊处理）
    #         # 这里假设所有短信内容相同
    #         datas = (codes[0], '5')
    #
    #         loop = asyncio.get_event_loop()
    #         resp = await loop.run_in_executor(
    #             thread_pool,
    #             self.sdk.sendMessage,
    #             tid, mobile, datas
    #         )
    #
    #         response_data = self._parse_response(resp)
    #
    #         if response_data.get('statusCode') == '000000':
    #             logger.info(f"荣联云批量短信发送成功: {len(phones)}条")
    #             return True, response_data
    #         else:
    #             logger.error(f"荣联云批量短信发送失败: {response_data}")
    #             return False, response_data
    #
    #     except Exception as e:
    #         logger.error(f"批量短信发送异常: {e}")
    #         return False, {'error': str(e)}
    #
    # def send_sms_sync(self, phone, code):
    #     """
    #     同步发送短信（用于非异步环境）
    #     """
    #     return self._send_sms_sync(phone, code)


# 单例实例
sms_service = RonglianSMSService()